<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="6">
              <a-form-item label="对账单编号">
                <a-input v-model="queryParam.accountCode" placeholder="请输入对账单编号"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="客户名称">
                <a-input v-model="queryParam.customerName" placeholder="请输入客户名称"/>
              </a-form-item>
            </a-col>
            <a-col>
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 收款 -->
    <biz-payment-add-form v-if="showAddModal" ref="bizPaymentAddForm" :payOptions="payOptions" @ok="getList" @close="showAddModal = false" />
      <advance-table
      :customRow="customRow"
      :components="drag(columns)"
       title="对账单" :pagination="{
        current: queryParam.pageNum,
        pageSize: queryParam.pageSize,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        pageSizeOptions:pageSizeOptions,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: changeSize,
        onShowSizeChange: onShowSizeChange
      }" tableKey="base-bizOrder-index-table" @change="handleTableChange" rowKey="id" @refresh="getList"
        :row-selection="{ selectedRowKeys: selectedRowKeys,getCheckboxProps:getCheckboxProps, onChange: onSelectChange,type:'radio' }"
        :columns="columns" :data-source="dataList" :loading="loading" :format-conditions="true">
        
        <div class="table-operations" slot="button">
          <a-button type="primary"  @click='print'>
            <a-icon />打印
          </a-button>
          <a-button type="primary"  @click='exportExcel'>
            <a-icon />导出
          </a-button>
        </div>
        <span slot="operation" slot-scope="{record}" v-if="record.id">
          
          <a @click="openSettle = true;currentInfo=record"  v-hasPermi="['biz:bizPayment:add']">
            结算标签
          </a>
          
          <span v-if="record.status == 0 || record.status == 1" v-hasPermi="['biz:bizPayment:add']">
            
            <a-divider type="vertical" />
            <a @click="handlePayment(record,1)" >
              收款
            </a>
          </span>
          <span v-hasPermi="['biz:bizcustomeraccount:remove']" v-if="record.status == 0">
            <a-divider type="vertical" />
            <a @click="handlePaymentRemove(record)"  >
              删除
            </a>
          </span>
        </span>
        <span slot="statusSlot" slot-scope="{record}" v-if="record.id">
          <span v-if="record.status == 0">待收款</span>
          <span v-else-if="record.status == 1">部分收款</span>
          <span v-else>已收款</span>
        </span>
        <span slot="accountTypeSlot" slot-scope="{record}" v-if="record.id">
          <span v-if="record.accountType == 1">月结</span>
          <span v-else-if="record.accountType == 2">现结</span>
          <span v-else>-</span>
        </span>
        
      </advance-table>
    </a-card>
    
    <ant-modal
      :visible="open"
      modal-title="打印采购明细表"
      :adjust-size="true"
      @cancel="cancel"
      modalHeight="550"
      modalWidth="1000">
      <a-row slot="content">
        <iframe height='425' width='985' style='border:none;min-height: 100vh;width: 100%;' :src='setUrl' ></iframe>
      </a-row>
      <div slot="footer">
        <a-button @click="cancel">关闭</a-button>
      </div>
    </ant-modal>
    <ant-modal
      :visible="openSettle"
      modal-title="结算标签"
      :adjust-size="false"
      @cancel="cancel"
      modalHeight="100"
      modalWidth="300">
      <a-row slot="content">
        <a-select placeholder="请选择费用类型" v-model="accountType" style="width: 100%" allow-clear >
                  <a-select-option :value="1">月结</a-select-option>
                  <a-select-option :value="2">现结</a-select-option>
            </a-select>
      </a-row>

      <div slot="footer">
        <a-button @click="openSettle = false">关闭</a-button>
        <a-button :loading="settleLoading" @click="handleSettle()" type="primary">保存</a-button>
      </div>
    </ant-modal>
  </div>
</template>
<script>
import { listBizCustomerAccount,delBizCustomerAccount ,exportExcelBizCustomerAccountDetail,updateAccountType } from '@/api/biz/bizCustomerAccount'
import { getInitData } from '@/api/biz/bizPurchase'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import BizPaymentAddForm from '@/views/biz/bizcustomeraccount/modules/BizPaymentAddForm.vue'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import AntModal from '@/components/pt/dialog/AntModal'
import storage from 'store'

import listMixin from '@/mixins/listMixin';
export default {
  name: 'BizCustomerPayable',
  components: {
    AdvanceTable,
    BizPaymentAddForm,
    AntModal
  },
  mixins:[tableDragResizeMixin,listMixin],
  data() {
    return {
      // 打印弹窗
      open:false,
      printUrl:'/api/biz/bizcustomeraccount/export?Authorization='+storage.get(ACCESS_TOKEN),
      printUrlPath:'/api/biz/bizcustomeraccount/export?Authorization='+storage.get(ACCESS_TOKEN),
      setUrl:'',
      showAddModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      accountType:1,
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      openSettle:false,
      currentInfo:{},
      settleLoading:false,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 表格数据
      dataList: [],
      payOptions: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 11,
        accountCode: undefined,
        customerName: undefined,
      },
      
      pageSizeOptions: ['11', '21', '31', '101', '201'],
      columns: [
        {
          title: '对账单编号',
          dataIndex:'accountCode',
          align: 'center'
        },
        {
          title: '客户',
          dataIndex:'customerName',
          align: 'center'
        },
        {
          title: '总金额',
          dataIndex:'totalAmount',
          align: 'center'
        },
        {
          title: '收款金额',
          dataIndex:'payAmount',
          align: 'center'
        },
        {
          title: '实收金额',
          dataIndex:'actualAmount',
          align: 'center'
        },
        {
          title: '抹零金额',
          dataIndex:'wipeAmount',
          align: 'center'
        },
        
        {
          title: '结算标签',
          dataIndex:'accountType',
          align: 'center',
          scopedSlots: { customRender: 'accountTypeSlot' }
        },
        {
          title: '状态',
          dataIndex:'status',
          align: 'center',
          scopedSlots: { customRender: 'statusSlot' }
        },
        {
          title: '操作',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  created() {
    
    this.getList()
    getInitData('pay_type').then(response => {
      this.payOptions = response.data.pay_type
    })
  },
  methods: {
    
    
    /** 导出按钮操作 */
    exportExcel () {
      var that = this,param
      if(this.selectedRows.length){
        param = {
          accountCode:this.selectedRows[0].accountCode
        }
      }else{
        return this.$message.error('请选择一条数据')
      }
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          return exportExcelBizCustomerAccountDetail(param)
            .then(response => {
              that.download(response.msg)
              that.$message.success(
                '导出成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    /** 查询销售单列表 */
    getList() {
      this.loading = true
      let param = this.getQueryParam()
      listBizCustomerAccount(param).then(response => {
        this.dataList = response.data.list
        this.total = response.data.total
        this.loading = false
        this.tableAddTotalRow(this.columns,this.dataList)
      })
    },
    handlePayment(row,type = null){
      this.showAddModal = true
      this.$nextTick(() => {
        let data = {customerId:row.customerId,customerName:row.customerName,accountCode:row.accountCode,totalAmount:row.totalAmount};
        row.queryType = type
        this.$refs.bizPaymentAddForm.handlePayment(row,type)
      })
    },
    handleSettle(){
      const updateType = (data)=>updateAccountType(data).then(res=>{
            this.settleLoading = false
            if(res.code == 200) {
              this.$message.success(
                '操作成功',
                3
              )
              this.openSettle = false
              this.getList()
            }else{
              this.message.error(res.msg)
            }
          }).catch(()=>{
            this.settleLoading = false
          })
          let data ={
            id:this.currentInfo.id,
            accountType:this.accountType
          }
          this.settleLoading = true
          updateType(data)
      // this.$confirm({
      //   title: '确认结算?',
      //   okText:'月结',
      //   cancelText:'现结',
      //   onOk: () => {
      //     let data = {
      //       id:row.id,
      //       accountType:type
      //     }
      //     updateType(data)
      //   },
      //   onCancel: () => {
      //     let data = {
      //       id:row.id,
      //       accountType:type
      //     }
      //     updateType(data)
      //   },
      // })
    },
    
    handlePaymentRemove(row){
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          delBizCustomerAccount(row.id).then(res=>{
            if(res.code == 200) {
              this.$message.success(
                '删除成功',
                3
              )
              this.getList()
            }else{
              this.message.error(res.msg)
            }
          })
        }
      })
    },
    cancel(){
      this.open = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        supplierName: undefined

      }
      this.handleQuery()
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = size
      this.getList()
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    handleTableChange(pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.queryParam.orderByColumn = 'a.' + sorter.field
        this.queryParam.isAsc = sorter.order
      }
      this.getList()
    },
    
    print() {
      let param = {}
      if(this.selectedRows.length){
        param = {
          accountCode:this.selectedRows[0].accountCode
        }
      }else{
        return this.$message.error('请选择一条数据')
      }
      this.setUrl =  this.printUrl + '&accountCode='+ param.accountCode
      this.open=true;
      this.$nextTick(()=>{
        setTimeout(()=>{
          var button = document.getElementById("download");
            console.log('button :>> ', button);
          button.addEventListener("click", ()=>{
            alert("Button clicked!");
          });
        },2000);
      })
    },
    customRow (record) {
        return {
          on: {
            dblclick: () => {
              this.$nextTick(() => {
                if(record.id) this.handlePayment(record,0)
              })
            }
          }
        }
      }
  }
}
</script>
